﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Sprout.Repository
{
    /// <summary>
    /// 事务处理类
    /// </summary>
    internal sealed class TransactionProcess
    {
        public TransactionProcess()
        {
            TransMaps = new Dictionary<string, TransactionMap>();
            DataSourceMaps = new Dictionary<string, string>();
        }
        /// <summary>
        /// dataSource 对应事务 字典
        /// </summary>
        Dictionary<string, TransactionMap> TransMaps;

        //不同连接名 同一连接地址对应字典
        Dictionary<string, string> DataSourceMaps;

        /// <summary>
        /// 获取或设置事务
        /// </summary>
        /// <param name="dataSource"></param>
        /// <returns></returns>
        public TransactionMap GetOrAddTransaction(string dataSource)
        {
            dataSource = DataSetting.Instance.GetDataSource(dataSource);
            if (TransMaps.ContainsKey(dataSource))
            {
                return TransMaps[dataSource];
            }
            //判断数据库连接是否一致
            if (DataSourceMaps.ContainsKey(dataSource))
            {
                return TransMaps[DataSourceMaps[dataSource]];
            }
            var option = DataSetting.Instance.GetConnectionOption(dataSource);
            foreach (var item in TransMaps)
            {
                //如果连接字符串完全一致
                if (item.Value.ConnectionSetting.ConnectionString.ToLower() == option.ConnectionString.ToLower())
                {
                    DataSourceMaps.Add(dataSource, item.Key);
                    break;
                }
                //如果连接地址一样，数据库一样
                else if (item.Value.ConnectionSetting.Address.ToLower() == option.Address.ToLower() && item.Value.ConnectionSetting.Database.ToLower() == option.Database.ToLower())
                {
                    DataSourceMaps.Add(dataSource, item.Key);
                    break;
                }
            }
            if (DataSourceMaps.ContainsKey(dataSource))
            {
                return TransMaps[DataSourceMaps[dataSource]];
            }

            //加入事务字典中
            var connection = DataSetting.Instance.GetConnection(dataSource);
            TransMaps.Add(dataSource, new TransactionMap(option, connection));

            return TransMaps[dataSource];
        }

        /// <summary>
        /// 提交全局事务
        /// </summary>
        public void Commit()
        {
            foreach (var item in TransMaps)
            {
                item.Value.Commit();
            }
        }
        /// <summary>
        /// 回滚全局事务
        /// </summary>
        public void Rollback()
        {
            foreach (var item in TransMaps)
            {
                item.Value.Rollback();
            }
        }
    }
}
